//
//  RootViewController.m
//  Shadeco
//
//  Created by Le Thanh Hai on 9/13/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ContentViewController.h"


@implementation ContentViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/

-(void)showOverlayWithFrame:(CGRect)Frame 
{    
    if (![marque actionForKey:@"linePhase"]) {
        CABasicAnimation *dashAnimation;
        dashAnimation = [CABasicAnimation animationWithKeyPath:@"lineDashPhase"];
        [dashAnimation setFromValue:[NSNumber numberWithFloat:0.0f]];
        [dashAnimation setToValue:[NSNumber numberWithFloat:15.0f]];
        [dashAnimation setDuration:0.5f];
        [dashAnimation setRepeatCount:HUGE_VALF];
        [marque addAnimation:dashAnimation forKey:@"linePhase"];
    }
    marque.frame = CGRectMake(0, 0, 0, 0);
    
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathAddRect(path, NULL, Frame);
    [marque setPath:path];
    CGPathRelease(path);    
//    marque.hidden = NO;  
}


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{    
    [super viewDidLoad];
    
    // Create image view
    imageView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    imageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview: imageView];
    
    //
    mainImage = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", @"maria.png"]]];
    mainImage.frame = CGRectMake(0, 0, 320, 480);
    [imageView addSubview:mainImage];
    mainImage.contentMode = UIViewContentModeScaleAspectFill;
    [mainImage release];
    
    // Create frame view
    frameView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    frameView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:frameView];
    
    //
    mainFrame = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", @"style1_4.png"]]];
    mainFrame.frame = CGRectMake(0, 0, 320, 480);
    [frameView addSubview:mainFrame];

    
    // Create menu view
    menuView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
    menuView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:menuView];
    
    if (!marque) {
        marque = [[CAShapeLayer layer] retain];
        marque.fillColor = [[UIColor clearColor] CGColor];
        marque.strokeColor = [[UIColor blackColor] CGColor];
        marque.lineWidth = 1.0f;
        marque.lineJoin = kCALineCapSquare;
        marque.lineDashPattern = [NSArray arrayWithObjects:[NSNumber numberWithInt:10],[NSNumber numberWithInt:5], nil];
    }
    [[menuView layer] addSublayer:marque];
    
    // Add notify
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addFrame:) name:@"addFrameToView" object:nil];	
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addStamp:) name:@"addStampToView" object:nil];	
    
    
    // add the trash
    trash = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"trash.png"]];
    [menuView addSubview:trash];
    trash.frame = CGRectMake(320 - trash.frame.size.width, 480 - trash.frame.size.height, trash.frame.size.width, trash.frame.size.height);
    trash.hidden = YES;
    
    UIRotationGestureRecognizer *rotationGesture = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotatePiece:)];
    [menuView addGestureRecognizer:rotationGesture];
    [rotationGesture release];
    
    UIPinchGestureRecognizer *pinchGesture = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(scalePiece:)];
    [pinchGesture setDelegate:self];
    [menuView addGestureRecognizer:pinchGesture];
    [pinchGesture release];
    
    UIPanGestureRecognizer *panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panPiece:)];
    [panGesture setMaximumNumberOfTouches:2];
    [panGesture setDelegate:self];
    [menuView addGestureRecognizer:panGesture];
    [panGesture release];
    
    UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(delPiece:)];
    [longPressGesture setDelegate:self];
    [menuView addGestureRecognizer:longPressGesture];
    [longPressGesture release];
    
    UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tappedDraw:)];
	[tapRecognizer setNumberOfTapsRequired:1];
	[tapRecognizer setDelegate:self];
	[menuView addGestureRecognizer:tapRecognizer];
}


- (void)tappedDraw:(UIPinchGestureRecognizer *)gestureRecognizer
{
    NSLog(@"tap draw view");
    marque.hidden = YES;
    curentViewTap = nil;
}

// display a menu with a single item to allow the piece's transform to be reset
- (void)delPiece:(UILongPressGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan) 
    {   
        trash.hidden = NO;
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.1];
        // other animations goes here    
        trash.frame = CGRectMake(224, 384, 96, 96);
        // other animations goes here
        [UIView commitAnimations];
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:0.1];    
        trash.frame = CGRectMake(272, 432, 48, 48);
        [UIView commitAnimations];
        NSLog(@"trash");
    }
    if([gestureRecognizer state] == UIGestureRecognizerStateChanged)
    {
        if (curentViewTap.frame.origin.x + curentViewTap.frame.size.width / 2 > 272 && curentViewTap.frame.origin.y + curentViewTap.frame.size.height /2 > 432) 
        {
            [curentViewTap removeFromSuperview];
            trash.hidden = YES;
        }    
    }
    if([gestureRecognizer state] == UIGestureRecognizerStateEnded)
    {
        marque.hidden = YES;
    }
}


- (void)panPiece:(UIPanGestureRecognizer *)gestureRecognizer
{    
    [menuView bringSubviewToFront:curentViewTap];
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        CGPoint translation = [gestureRecognizer translationInView:[curentViewTap superview]];
        
        [curentViewTap setCenter:CGPointMake([curentViewTap center].x + translation.x, [curentViewTap center].y + translation.y)];
        [gestureRecognizer setTranslation:CGPointZero inView:[curentViewTap superview]];
    }
    [self showOverlayWithFrame: curentViewTap.frame];   
}



- (void)rotatePiece:(UIRotationGestureRecognizer *)gestureRecognizer
{
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        curentViewTap.transform = CGAffineTransformRotate([curentViewTap transform], [gestureRecognizer rotation]);
        [gestureRecognizer setRotation:0];
    }
    [self showOverlayWithFrame: curentViewTap.frame];
}


- (void)scalePiece:(UIPinchGestureRecognizer *)gestureRecognizer
{    
    if ([gestureRecognizer state] == UIGestureRecognizerStateBegan || [gestureRecognizer state] == UIGestureRecognizerStateChanged) {
        curentViewTap.transform = CGAffineTransformScale([curentViewTap transform], [gestureRecognizer scale], [gestureRecognizer scale]);
        [gestureRecognizer setScale:1];
    }
    [self showOverlayWithFrame: curentViewTap.frame];
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{    
    // if the gesture recognizers are on different views, don't allow simultaneous recognition
    if (gestureRecognizer.view != otherGestureRecognizer.view)
        return NO;
    return YES;
}



-(void)addStamp:(NSNotification *)notification
{
    NSLog(@"%@", notification.object);

    UIView *holderView = [[UIView alloc] init];
	[holderView addSubview:[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@", [NSString stringWithFormat:@"%@", notification.object]]]]];
	holderView.frame = CGRectMake(120, 200, 64, 64);
	UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapped:)];
	[tapRecognizer setNumberOfTapsRequired:1];
	[tapRecognizer setDelegate:self];
	[holderView addGestureRecognizer:tapRecognizer];	
	
	[menuView addSubview:holderView];
    [stamp.view removeFromSuperview];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];
}

-(void)tapped:(UIPinchGestureRecognizer *)gestureRecognizer
{
    marque.hidden = NO;
	NSLog(@"tapped");
    curentViewTap = [gestureRecognizer view];
    [self showOverlayWithFrame:curentViewTap.frame];
}



/*--*/
-(IBAction) takePhoto:(id) sender {
	UIImagePickerController * picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
	
	[self presentModalViewController:picker animated:YES];
}

-(IBAction) getPhoto:(id) sender {
	UIImagePickerController * picker = [[UIImagePickerController alloc] init];
	picker.delegate = self;
	
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
	
	[self presentModalViewController:picker animated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	[picker dismissModalViewControllerAnimated:YES];
	mainImage.image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
}
/************************/
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if ([[touches anyObject] tapCount] > 1) {        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];
    }
}

-(void)addFrame:(NSNotification *)notification
{
    NSLog(@"%@", notification.object);	
	[[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];	
    mainFrame.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@",notification.object]];
}

- (void)PenSelected: (id)sender
{
    NSLog(@"%@", @"Pen Selected");
}

- (void)TextSelected: (id)sender
{
    NSLog(@"%@", @"Text Selected");
}

- (void)BrushSelected: (id)sender
{
    NSLog(@"%@", @"Brush Selected");
}

- (void)ColorSelected: (id)sender
{
    NSLog(@"%@", @"Color Selected");
}

- (void)LibSelected: (id)sender
{
    NSLog(@"%@", @"Lib Selected");
    [self getPhoto:sender];    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];
}

- (void)CameraSelected: (id)sender
{
    NSLog(@"%@", @"Camera Selected");
    [self takePhoto:sender];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];
}

- (void)SaveSelected: (id)sender
{
    NSLog(@"%@", @"Save Selected");
    UIGraphicsBeginImageContext(self.view.bounds.size);	
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    UIImageWriteToSavedPhotosAlbum(viewImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];
}


- (void)MailSelected: (id)sender
{
    NSLog(@"%@", @"Mail Selected");
    [[NSNotificationCenter defaultCenter] postNotificationName:@"HideViewMenu" object:@"HideView"];
    [self showEmail:sender];
}

- (void)LanguageSelected: (id)sender
{
    NSLog(@"%@", @"Language Selected");
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
	UIAlertView *alert;	 
	if (error)
		alert = [[UIAlertView alloc] initWithTitle:@"Error" 
										   message:@"Unable to save image to Photo Album." 
										  delegate:self cancelButtonTitle:@"Ok" 
								 otherButtonTitles:nil];
	else // All is well
		alert = [[UIAlertView alloc] initWithTitle:@"Success" 
										   message:@"Image saved to Photo Album." 
										  delegate:self cancelButtonTitle:@"Ok" 
								 otherButtonTitles:nil];
	[alert show];
	[alert release];
}

// Displays an email composition interface inside the application. Populates all the Mail fields. 
-(void)showEmail:(id)sender
{	
	Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
	if (mailClass != nil)
	{
		// We must always check whether the current device is configured for sending emails
		if ([mailClass canSendMail])
		{
			[self displayComposerSheet];
		}
		else
		{
			[self launchMailAppOnDevice];
		}
	}
	else
	{
		[self launchMailAppOnDevice];
	}
}
-(void)displayComposerSheet 
{
	MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
	picker.mailComposeDelegate = self;
	
	[picker setSubject:@"Send from Shadeco!"];
    
    // Making a image
	UIGraphicsBeginImageContext(self.view.bounds.size);
    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *atachImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    // Attach an image to the email
    NSData *dataSend = UIImagePNGRepresentation(atachImage);
    [picker addAttachmentData:dataSend mimeType:@"image/png" fileName:@"shadeco"];
    
    
	// Fill out the email body text
	NSString *emailBody = @"Send from Shadeco!";
	[picker setMessageBody:emailBody isHTML:NO];
	
	[self presentModalViewController:picker animated:YES];
    [picker release];
}


// Dismisses the email composition interface when users tap Cancel or Send. Proceeds to update the message field with the result of the operation.
- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error 
{	
	// Notifies users about errors associated with the interface
	switch (result)
	{
		case MFMailComposeResultCancelled:
			message = @"Photo canceled";
			break;
		case MFMailComposeResultSaved:
			message = @"Photo saved";
			break;
		case MFMailComposeResultSent:
			message = @"Photo sent";
			break;
		case MFMailComposeResultFailed:
			message = @"Photo failed";
			break;
		default:
			message = @"Photo not sent";
			break;
	}
	[self dismissModalViewControllerAnimated:YES];    
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Send photo" 
                                              message:message 
										      delegate:self cancelButtonTitle:@"Ok" 
                                              otherButtonTitles:nil];

	[alert show];
	[alert release];
}
#pragma mark -
#pragma mark Workaround

// Launches the Mail application on the device.
-(void)launchMailAppOnDevice
{
	NSString *recipients = @"mailto:first@example.com?cc=second@example.com,third@example.com&subject=Send from Shadeco!";
	NSString *body = @"&body=Send from Shadeco!";
	
	NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
	email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
	
	[[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
